package com.fourtwoeight.controllers;

import java.io.File;
import java.io.FileWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;



public class UpdateNotes extends DisplayThumbs {


    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {

        logger = LogFactory.getLog(this.getClass());

        String notesFileName = request.getParameter(WebConstants.IMAGE_NOTES_FILENAME);

        String notes = request.getParameter(WebConstants.IMAGE_NOTES);

        logger.debug("Will store notes in: " + notesFileName);
        logger.debug("Notes: " + notes);

        FileWriter out = null;
        try {

            File outputFile = new File(notesFileName);

            if (!outputFile.exists()) {
                File outputDirectory = new File(outputFile.getParent());

                if (!outputDirectory.exists()) {
                    outputDirectory.mkdir();
                }
            }
            out = new FileWriter(outputFile, false);

            if (notes != null && out != null) {
                out.write(notes);
                out.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Couldn't write notes: " + e.getMessage());
            return mapping.findForward(WebConstants.FAILURE);
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("Couldn't close output buufer when writing: " + notes);
                return mapping.findForward(WebConstants.FAILURE);
            }
        }

        request.getSession().setAttribute(WebConstants.FILE, request.getParameter(WebConstants.FILE));
        return mapping.findForward(WebConstants.SUCCESS);
    }

}

